package com.ishare.common.service.base.impl;

import com.ishare.common.constant.ScoreChangeType;
import com.ishare.common.dao.UserDao;
import com.ishare.common.dao.UserScoreChangeDetailDao;
import com.ishare.common.entity.User;
import com.ishare.common.entity.UserScoreChangeDetail;
import com.ishare.common.service.base.ScoreService;
import com.ishare.common.service.base.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author 李嘉宾
 * @since 1.0.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ScoreServiceImpl implements ScoreService {

    @Resource
    private UserService userService;

    @Resource
    private UserDao userDao;

    @Resource
    private UserScoreChangeDetailDao userScoreChangeDetailDao;

    @Override
    public boolean changeUserScore(ScoreChangeType scoreChangeType, Long changeScore, Integer fromId, Integer toUserId) {
        //查询用户当前的分值
        User preUserData = userService.getUserById(toUserId);
        Long preScore = preUserData.getScore();
        //计算更改后的分值
        Long afterScore = preScore + changeScore;
        //增加分值
        int flag = userDao.addUserScore(toUserId, changeScore);
        if (flag != 1) {
            //沒有更新成功
            return false;
        }
        //更新成功
        //构建变动详情
        UserScoreChangeDetail scoreChangeDetail = UserScoreChangeDetail.builder()
                .fromId(fromId)
                .afterScore(afterScore)
                .changeDesc(scoreChangeType.getScoreDesc())
                .changeType(scoreChangeType.getChangeType())
                .insertTime(new Date())
                .updateTime(new Date())
                .userId(toUserId)
                .changeScore(changeScore)
                .preScore(preScore).build();
        //插入详情信息
        userScoreChangeDetailDao.save(scoreChangeDetail);
        return true;
    }

}
